/*
 * LoginRegister handles Login and Register Function at the startup phase of the application
 */
package com.user;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.configuration.Configuration;

import android.content.Context;
import android.telephony.TelephonyManager;
import android.util.Log;


public class LoginRegister {
	private JSONParser jsonParser;
    
    private static String loginRegisterURL 	= "http://128.199.214.245/android/android_login_register.php";
    private static String authURL 			= "http://128.199.214.245/android/android_auth.php";
    
    private static String login_tag = "login";
    private static String register_tag = "register";
    
    //For isUserLoggedIn
    private JSONObject json;
    List<NameValuePair> params2;
    
    //Constructor
    public LoginRegister(){
        jsonParser = new JSONParser();
    }
    //Constructor END
    
    /* 
     * authUser send a POST request to authURL
     * with telephone and passcode inside
     * It returns a json object with json encoded message from server to tell whether
     * passcode is correct or not		
     */ 
    public JSONObject authUser(String telephone,String passcode,Context context){
    	// Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        
        params.add(new BasicNameValuePair("telephone",telephone));
        params.add(new BasicNameValuePair("passcode",passcode));
        params.add(new BasicNameValuePair("imei",getImei(context)));
        
        
        //Use POST method to send telephone and passcode to authURL
		JSONObject json = jsonParser.makeHttpRequest(authURL,"POST",params);
		
		return json;
    }
    //authUser END
     
    
    /* 
     * loginRegisterUser both logins and registers user
     * It sends a POST request to loginRegisterURL with telephone and IMEI
     * It returns a json object with json encoded message from server to tell whether successful or not
     */
    public JSONObject loginRegisterUser(String telephone,Context context){
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        
		params.add(new BasicNameValuePair("telephone", telephone));
        params.add(new BasicNameValuePair("imei", getImei(context)));
        //User POST method to send telephone and IMEI to loginRegisterURL
        JSONObject json = jsonParser.makeHttpRequest(loginRegisterURL,"POST", params);
        return json;
    }
    //loginRegisterUser END
     
    
    /* 
     * isUserLoggedIn checks whether user have logged in at loading page with the information inside TABLE_CONTACTS
     * true 	: login successful
     * false	: login fail
     */
    public boolean isUserLoggedIn(Context context,Boolean isLogin){
    	
    	if(Configuration.showLog){
    		Log.d("LoginRegister","isUserLoggedIn");
    	}
    	
        DatabaseHandler db = new DatabaseHandler(context);
        
        List<Contact> contactList = db.getAllContacts();
        
        // contactList.isEmpty() : No user data in TABLE_CONTACT in the database
        // contactList.size() >1 : More than TABLE_CONTACT, error
        if(contactList.isEmpty() || contactList.size() > 1){
        	//Delete all information inside the Database
        	logoutUser(context);
        	return false;
        }
        
        for(Contact contact : contactList){
        	params2 = new ArrayList<NameValuePair>();
            
            //User POST method to send telephone and imei to loginRegisterURL
			params2.add(new BasicNameValuePair("id", Integer.toString(contact.getID())));
            params2.add(new BasicNameValuePair("telephone", contact.getTelephone()));
            params2.add(new BasicNameValuePair("imei", getImei(context)));
            if(isLogin){
            	params2.add(new BasicNameValuePair("login", "1"));
            }
            
          //Start a new thread to attempt Login (requirement when connecting online)
			Thread attemptThread = new Thread(new Runnable(){  
				public void run(){  
					json = jsonParser.makeHttpRequest(loginRegisterURL,"POST", params2);
				}
			});  
			attemptThread.start();
			
			while(attemptThread.isAlive()){
	        	//Waiting to get server response
	        }
            
            
            
            //Messages to be returned by server
            String KEY_MESSAGE	= "MESSAGE";
            String KEY_SUCCESS 	= "NEXT";
            String KEY_FAIL		= "FAIL";
            
            //Analysis return message
            try {
				if(json.getString(KEY_MESSAGE)!= null){
					if(json.getString(KEY_MESSAGE).equalsIgnoreCase(KEY_SUCCESS)){
						return true;
					}else if(json.getString(KEY_MESSAGE).equalsIgnoreCase(KEY_FAIL)){
						//Delete all information inside the Database
			        	logoutUser(context);
						return false;
					}else{
						//Unknown return
						logoutUser(context);
						return false;
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
				if(Configuration.showLog){
					Log.d("LoginRegister Error","Unable to capture return message");
				}
			}
        }
        
        return false;
    }
     
    /* 
     * logoutUser logout user by clearing TABLE_CONTACTS 
     * Function to logout user
     * Reset Database
     */
    public boolean logoutUser(Context context){
        DatabaseHandler db = new DatabaseHandler(context);
        db.deleteAllContacts();
        return true;
    }
    
    /*
     * return the IMEI of the device
     */
    public static String getImei(Context context){
    	TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
    	String imei = tm.getDeviceId();
    	if(Configuration.showLog){
    		Log.d("LoginRegister","IMEI = " + imei);
    	}
		return imei;
    }

}
